<?

require_once("mysql.php");

function google_extract_places_search_results($goog) {

    $places = array();
	
    $temp = $goog['predictions'];
	
	if (is_array($temp)) {
	    $c = 0;
		foreach ($temp as $slice) {
            if ($c++ > 2) break;
            $s  = str_ireplace(", United States", "", $slice['description']);
			array_push($places, $s);
		}
	
    	return $places;
	
	} else {
		return array("-1");
	}
}


$s = ESC(strtolower(trim($_GET['search'])));
$q = "SELECT * FROM places WHERE name='%s'";
$q = sprintf($q, $s);
$r = MYSQL_Q($q);
$c = mysql_num_rows($r);


if ($c == 0 || !$r || @$_GET['location']) {

    // Didn't find it in our local cache. Search it in Google

    $APPKEY = "AIzaSyBQZ7w1bdCtYlJ1XYHCw6CWhuwUybKs6fs";
    $SEARCH = "https://maps.googleapis.com/maps/api/place/autocomplete/json?location=".@$_GET['location']."&radius=".@$_GET['radius']."&types=geocode&language=en&sensor=true&key=".$APPKEY."&input=".urlencode($_GET['search']);

    $reply = json_decode(file_get_contents($SEARCH), true);

    //TODO:  make sure reply is sane

    $reply_ex = google_extract_places_search_results($reply);

    echo json_encode($reply_ex);

    if (@$_GET['location']) die();

    $q = "INSERT INTO places (name, suggestions, time, count) VALUES ('%s', '%s', UNIX_TIMESTAMP(NOW()), 0)";
    $q = sprintf($q, ESC($s), ESC(json_encode($reply_ex)));
    MYSQL_Q($q);

} else {

    $entry = mysql_fetch_assoc($r);

    echo stripslashes($entry['suggestions']);

    MYSQL_Q("UPDATE places SET count=".($entry['count']+1)." WHERE name='".$s."'");


}


?>
